<template>
    <div class="login-body">
        <div class="wrapper">
            <form v-if="isLogin" :model="loginForm">
                <h1>Login</h1>
                <div class="input-box">
                    <input v-model="loginForm.account" type="text" placeholder="UserName" required>
                    <img src="../components/icons/person.svg" alt="">
                </div>
                <div class="input-box">
                    <input v-model="loginForm.password" type="password" placeholder="Password" required>
                    <img src="../components/icons/lock.svg" alt="">
                </div>
                <div class="remember-forgot">
                    <label>
                        <input type="checkbox"> Remember me
                    </label>
                    <a href="#">Forgot password?</a>
                </div>
                <button class="btn" type="button" @click="handleLogin">Login</button>
                <div class="register-link">
                    <p>Dot't have an account?<a href="#" @click.prevent="toggleForm"> Register</a></p>
                </div>
            </form>

            <!-- 注册表单 -->
            <form v-else :model="registerForm">
                <h1>Register</h1>
                <div class="input-box">
                    <input v-model="registerForm.Account" type="text" placeholder="Username" required>
                    <img src="@/assets/icons/person.svg" alt="">
                </div>
                <div class="input-box">
                    <input v-model="registerForm.password" :type="showPassword ? 'text' : 'password'"
                        placeholder="Password" required>
                    <img :src="showPassword ? icons.eye : icons.eye_off" class="password-toggle"
                        @click="togglePasswordVisibility" alt="">
                </div>
                <div class="input-box">
                    <input v-model="registerForm.confirmPassword" :type="showPassword ? 'text' : 'password'"
                        placeholder="Confirm Password" required>
                    <img src="@/assets/icons/lock.svg" alt="">
                </div>
                <div class="input-box">
                    <input v-model="registerForm.email" type="email" placeholder="Email" required>
                    <img src="@/assets/icons/email.svg" alt="">
                </div>
                <div class="input-box">
                    <input v-model="registerForm.contactPhone" type="text" placeholder="Contact Phone" required>
                    <img src="@/assets/icons/phone.svg" alt="">
                </div>

                <button class="btn" type="button" @click="handleRegister">Register</button>
                <div class="register-link">
                    <p>Already have an account?<a href="#" @click.prevent="toggleForm"> Login</a></p>
                </div>
            </form>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { LoginUserInfo, RegisterUserInfo } from '@/api/UserInfoService';
import { ElMessage } from 'element-plus'
import { verifyAccountFormat, verifyEmailFormat, verifyPasswordStrength } from '@/utils/verification';
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router';
import { icons } from '@/assets/icons/icons';
import { getJwtToken } from '@/api/JwtToken';
import { useTokenStore } from '@/utils/stores/Global';

const router = useRouter()

const captchaUrl = ref('')
const refreshCaptcha = () => {
    captchaUrl.value = `/api/captcha?t=${Date.now()}`
}

onMounted(() => {
    refreshCaptcha()
})

const loading = ref(false)
const loginFormRef = ref()

const handleLogin = async () => {
    if (loginForm.account === '' || loginForm.password === '') return;

    const request = {
        account: loginForm.account,
        password: loginForm.password
    }

    const response = await getJwtToken(request.account, request.password)
    if (response.code === 200) {
        useTokenStore().token = response.data.token
        console.log("token:", useTokenStore().getToken())
        router.push('/Home')
    }
}

const loginForm = {
    account: localStorage.getItem('username') || '',
    password: '',
    captcha: '',
    rememberMe: !!localStorage.getItem('username')
}

watch(
    () => loginForm.rememberMe,
    (val) => {
        if (val) {
            localStorage.setItem('username', loginForm.account)
        } else {
            localStorage.removeItem('username')
        }
    }
)

// 切换登录/注册
const isLogin = ref(true)
const toggleForm = () => {
    isLogin.value = !isLogin.value
}

// 注册表单
const registerForm = {
    Account: '',
    password: '',
    email: '',
    confirmPassword: '',
    contactPhone: ''
}

//处理注册
const handleRegister = async () => {
    // 验证密码
    if (registerForm.password !== registerForm.confirmPassword) {
        ElMessage.error('两次输入的密码不一致')
        return
    }
    // 验证邮箱格式
    if (!verifyEmailFormat(registerForm.email)) {
        ElMessage.error('请输入有效的邮箱地址')
        return
    }
    // 验证密码强度
    if (!verifyPasswordStrength(registerForm.password)) {
        ElMessage.error('密码强度较弱，建议使用字母、数字和符号组合')
        return
    }
    // 验证账号格式
    if (!verifyAccountFormat(registerForm.Account)) {
        ElMessage.error('账号只能包含字母和数字')
        return
    }

    // 注册请求
    try {
        const request = {
            account: registerForm.Account,
            password: registerForm.password,
            email: registerForm.email,
            contactPhone: registerForm.contactPhone,
            permissions: ['user']
        }
        const response = await RegisterUserInfo(request)
        if (response.code === 200) {
            ElMessage.success('注册成功')
            isLogin.value = true
        }
    } catch (error) {
        ElMessage.error('注册失败')
    }
}

// 显示/隐藏密码
const showPassword = ref(false)
const togglePasswordVisibility = () => {
    showPassword.value = !showPassword.value
}
</script>

<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;

}

.login-body {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: url('@/assets/icons/login_background.jpg') no-repeat;
    background-size: cover;
    background-position: center;
}

.wrapper {
    width: 420px;
    background: transparent;
    border: 2px solid rgba(255, 255, 255, .2);
    backdrop-filter: blur(20px);
    box-shadow: 0 0 10px rgba(0, 0, 0, rgb(255, 255, 255, .2));
    color: #fff;
    border-radius: 10px;
    padding: 30px 40px;
}

.wrapper h1 {
    font-size: 36px;
    text-align: center;
}

.wrapper .input-box {
    position: relative;
    width: 100%;
    height: 50px;
    margin: 30px 0;
}

.input-box input {
    width: 100%;
    height: 100%;
    background: transparent;
    border: none;
    outline: none;
    border: 2px solid rgb(255, 255, 255, .2);
    border-radius: 40px;
    font-size: 16px;
    color: #fff;
    padding: 20px 45px 20px 20px;
}

.input-box input::placeholder {
    color: #fff;
}

.input-box img {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 20px;
}

.wrapper .remember-forgot {
    display: flex;
    justify-content: space-between;
    font-size: 14.5px;
    margin: -15px 0 15px;
}

.remember-forgot label input {
    accent-color: #fff;
    margin-right: 3px;
}

.remember-forgot a {
    color: #fff;
    text-decoration: none;
}

.remember-forgot a:hover {
    text-decoration: underline;
}

.wrapper .btn {
    width: 100%;
    height: 45px;
    background: #fff;
    border: none;
    outline: none;
    border-radius: 40px;
    box-shadow: 0 0 10px rgba(0, 0, 0, .1);
    cursor: pointer;
    font-size: 16px;
    color: #333;
    font-weight: 600;
}

.wrapper .register-link {
    font-size: 14.5px;
    text-align: center;
    margin: 20px 0 15px;
}

.register-link p a {
    color: #fff;
    text-decoration: none;
    font-weight: 600;
}

.register-link p a:hover {
    text-decoration: underline;
}

/* 添加表单切换动画 */
.wrapper form {
    transition: all 0.3s ease;
}

/* 可以添加更多动画效果 */
.wrapper form.slide-enter-active,
.wrapper form.slide-leave-active {
    transition: all 0.3s ease;
}

.wrapper form.slide-enter-from,
.wrapper form.slide-leave-to {
    opacity: 0;
    transform: translateX(30px);
}


.input-box .password-toggle {
    cursor: pointer;
}

/* 可选：添加hover效果 */
.input-box .password-toggle:hover {
    opacity: 0.8;
}
</style>